# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from .models import *
from reversion.admin import VersionAdmin
from django.utils import timezone
from mptt.admin import MPTTModelAdmin
from import_export.admin import ImportExportModelAdmin
# Register your models here.

class WaybillItemInline(admin.TabularInline):
    model = WaybillItem
    extra = 0
    #suit_classes = 'suit-tab suit-tab-cities'

@admin.register(Waybill)
class WaybillAdmin(VersionAdmin,ImportExportModelAdmin):
    list_display=('ticket_at','ticket','counterman','agent','start_place','end_place','other_cost','other_cost2','other_cost3','receipt_cost','collection_cost','payment_status','remark','receipt_ticket','status')
    inlines=[WaybillItemInline]
    list_filter=('ticket_at','counterman','agent','start_place','end_place','payment_status','receipt_ticket','status')
    def suit_row_attributes(self, obj, request):
        #return {'class': 'type-%s' % obj.type}
        css_class = {
            'new': 'success',
            'approving': 'warning',
            'approved': 'error',
            'need-edit': 'warning',
        }.get(obj.status)
        if css_class:
            return {'class': css_class, 'data': obj.ticket}
    def queryset(self, request):
        qs = super(WaybillAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs
        
        return qs.filter(added_by=request.user)
    def save_model(self, request, obj, form, change):
        #obj.receipt_cost=obj.other_cost or 0
        #for x in obj.items.all():
        #    obj.receipt_cost = obj.receipt_cost+ x.cost*x.quantity
        obj.created_by = request.user
        obj.updated_by = request.user
        obj.save()
    def approve_log(self,queryset,user,action):
        for x in queryset:
            ApproveLog.objects.create(created_by=user,action=action,waybill=x)
    def send_approve(self, request, queryset):
        rows_updated = queryset.update(status='approving', updated_by=request.user, updated_at=timezone.now())
        if rows_updated == 1:
            message_bit = "1条记录被"
        else:
            message_bit = "%s条记录被" % rows_updated
        self.approve_log(queryset,request.user,'送审')
        self.message_user(request, "%s成功送审." % message_bit)

    send_approve.short_description = "送审"
    def make_approved(self, request, queryset):
        rows_updated = queryset.update(status='approved', updated_by=request.user, updated_at=timezone.now())
        if rows_updated == 1:
            message_bit = "1条记录被"
        else:
            message_bit = "%s条记录被" % rows_updated
        self.approve_log(queryset,request.user,'审核')
        self.message_user(request, "%s成功审核." % message_bit)

    make_approved.short_description = "审核"
    def make_need_edit(self, request, queryset):
        rows_updated = queryset.update(status='need-edit', updated_by=request.user, updated_at=timezone.now())
        if rows_updated == 1:
            message_bit = "1条记录被"
        else:
            message_bit = "%s条记录被" % rows_updated
        self.approve_log(queryset,request.user,'驳回')
        self.message_user(request, "%s成功驳回." % message_bit)

    make_need_edit.short_description = "驳回"
    actions=[send_approve,make_approved,make_need_edit]
    
class WaybillPartItemInline(admin.TabularInline):
    model = WaybillPartItem
    extra = 0        

@admin.register(WaybillPart)
class WaybillPart(VersionAdmin):
    inlines=[WaybillPartItemInline]
    list_display=('waybill','clerk','carrier','carrier_phone','vehicle_count','start_place','end_place','other_cost','other_cost2','other_cost3','receipt_cost','collection_cost','payment_status','remark','payment_ticket')
    list_filter=('waybill','clerk','carrier','start_place','end_place','payment_status','payment_ticket')
    def save_model(self, request, obj, form, change):
        #obj.receipt_cost=obj.other_cost or 0
        #for x in obj.items.all():
        #    obj.receipt_cost = obj.receipt_cost+ x.cost*x.quantity
        obj.created_by = request.user
        obj.updated_by = request.user
        obj.save()
    def carrier_phone(self,obj):
        return obj.carrier.phone
    carrier_phone.short_description = '电话'
    def vehicle_count(self, obj):
        return obj.items.count()
    vehicle_count.short_description = '数量'
        
@admin.register(Country)
class CountryAdmin(VersionAdmin):
    list_display=('code','name')

@admin.register(Agent)
class AgentAdmin(VersionAdmin):
    list_display=('name','email','phone','address')
    search_fields=('name',)

@admin.register(Carrier)
class CarrierAdmin(VersionAdmin):
    list_display=('name','email','phone','address')
    search_fields=('name',)

@admin.register(Counterman)
class CountermanAdmin(VersionAdmin):
    list_display=('name','email','phone','address')
    search_fields=('name',)    

@admin.register(Brand)
class BrandAdmin(VersionAdmin):
    list_display=('name','country')
    list_filter=('country',)

@admin.register(Vehicle)
class VehicleAdmin(VersionAdmin):
    list_display=('brand','name','year','is_import')
    list_filter=('brand','is_import')

@admin.register(WaybillItem)
class WaybillItemAdmin(VersionAdmin):
    list_display=('waybill','vehicle','cost','vin')
    list_filter=('waybill',)

@admin.register(Clerk)
class ClerkAdmin(VersionAdmin):
    list_display=('name','email','phone','address')
    search_fields=('name',)

@admin.register(UserProfile)
class UserProfileAdmin(VersionAdmin):  
    list_display = ('user','company')

@admin.register(Company)
class CompanyAdmin(VersionAdmin):
    list_display=('name','rank','place')
    #mptt_level_indent = 20
    #list_editable = ('is_active',)
    sortable = 'sort_order'
    class Media:
        css = {
            "all": ("css/main.css",)
        }
        js = ("js/main.js",)
    def save_model(self, request, obj, form, change):
        if obj.id and obj.level=='headquarters':
            try:
                company  = Company.objects.get(level='headquarters')
                if obj.id!=company.id:
                    messages.set_level(request, messages.ERROR)
                    self.message_user(request, "只能有一个总部",messages.ERROR)
                else:
                    obj.save()
            except Company.DoesNotExist:
                obj.save()
        else:
            obj.save()
            
@admin.register(ApproveLog)
class ApproveLogAdmin(admin.ModelAdmin):
    list_display=('waybill','created_by','created_at','action')
    list_filter=('waybill','created_by','created_at','action')
    
# @admin.register(Category)   
# class CategoryAdmin(MPTTModelAdmin, SortableModelAdmin):
#     mptt_level_indent = 20
#     list_display = ('name', 'slug', 'is_active')
#     list_editable = ('is_active',)

#     # Specify name of sortable property
#     sortable = 'order'
